<template>
    <el-container>
        <el-main class="wrapper">
            <section class="panel cms-content">
                <div class="cms-btn-group" v-if="showTop==0">
                    <el-tabs v-model="item" @tab-click="handleClick">
                        <el-tab-pane label="文章发布形式" name="0">文章发布形式</el-tab-pane>
                        <el-tab-pane label="公众号形式" name="1">公众号形式</el-tab-pane>
                    </el-tabs>
                </div>
                <div class="panel-body" v-if="showMsg==0">
                    <el-form :model="formData" label-position="top" :rules="rules" ref="formData" label-width="100px"
                             class="demo-ruleForm">
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-form-item required prop="music_name">
                                    <el-input v-model="formData.music_name" placeholder="请填写音乐名称"></el-input>
                                </el-form-item>
                                <el-form-item required prop="music">
                                    <el-input v-model="formData.music" placeholder="请填写音乐编号"></el-input>
                                </el-form-item>
                                <el-form-item required class="background" prop="backimg">
                                    <el-popover
                                        placement="right"
                                        width="1000" v-model="backimgsShow"
                                        trigger="click">
                                        <el-row :gutter="20" class="backimgs">
                                            <el-col v-for="item in backimgs" :key="item.id" :span="6"
                                                    style="margin-bottom: 10px">
                                                <el-card :body-style="{ padding: '0px' }">
                                                    <img :src="item.img" style="width:100%;height:85px" alt="">
                                                    <div style="padding: 14px;">
                                                        <span>{{item.title}}</span>
                                                        <el-button @click="select(item)"
                                                                   style="float: right; padding: 3px 0" type="text"
                                                                   class="button">选 择
                                                        </el-button>
                                                    </div>
                                                </el-card>
                                            </el-col>
                                        </el-row>
                                        <el-button type="primary" slot="reference">选择背景图</el-button>
                                    </el-popover>
                                    <el-button class="button" style="margin-left: 20px;">{{backimgsTile}}</el-button>
                                </el-form-item>
                                <el-form-item required prop="hot" v-if="userInfo.id==1">
                                    <el-radio-group v-model="formData.hot">
                                        <el-radio border :label="1">正常</el-radio>
                                        <el-radio border :label="2" style="margin-left: 60px;">热门</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item required prop="lock">
                                    <el-radio-group v-model="formData.lock">
                                        <el-radio border :label="1">正常</el-radio>
                                        <el-radio border :label="2" style="margin-left: 60px;">锁定</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item required prop="status">
                                    <el-radio-group v-model="formData.status">
                                        <el-radio border :label="1">上架</el-radio>
                                        <el-radio border :label="2" style="margin-left: 60px;">下架</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item required prop="thumb">
                                    <el-row :gutter="20">
                                        <el-col :span="24" style="padding-left: 5px;">
                                            <el-form-item required label="封面图：" prop="thumb">
                                                <el-upload
                                                    class="index-avatar-uploader"
                                                    :action="upload"
                                                    :headers="myHeaders"
                                                    :show-file-list="false"
                                                    name="image"
                                                    :on-success="handleAvatarSuccess"
                                                    :before-upload="beforeAvatarUpload">
                                                    <img v-if="formData.thumb" :src="formData.thumb"
                                                         class="index-avatar">
                                                    <i v-else class="el-icon-plus index-avatar-uploader-icon"></i>
                                                </el-upload>

                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="24" style="margin-top:10px;">
                                            <el-tag type="danger" style="margin-bottom:10px;">上传封面图片格式只能是 JPG | PNG |
                                                GIF
                                            </el-tag>
                                            <el-tag type="danger" style="margin-bottom:10px;">上传封面图片大小不能超过 100KB!
                                            </el-tag>
                                            <el-tag type="danger" style="margin-bottom:10px;">上传的封面图宽高必须是 360*288 px !
                                            </el-tag>
                                        </el-col>
                                    </el-row>
                                </el-form-item>
                            </el-col>
                            <el-col :span="11">
                                <el-form-item required prop="title">
                                    <el-input style="width: 60%;top:-15px" v-bind:content="formData.title"
                                              v-model="formData.title" placeholder="请填写标题"></el-input>
                                    <el-color-picker
                                        v-model="formData.title_color"
                                        :predefine="predefineColors">
                                    </el-color-picker>
                                </el-form-item>
                                <el-form-item required prop="content">
                                    <vue-neditor-wrap ref="mobile" v-model="formData.content" @ready="ready"
                                                      :config="myConfig"
                                                      :destroy="false"></vue-neditor-wrap>

                                </el-form-item>
                                <div>
                                    <el-button style="float: right" type="primary" @click="update(formData)">保存发布
                                    </el-button>
                                    <el-button type="primary" @click="goback()">返回列表</el-button>
                                </div>
                            </el-col>
                            <el-col :span="7">
                                <div class="preview-art">
                                    <div class="phone-content"
                                         :style="{'background':formData.backimg ? 'url('+ formData.backimg +')' : '#fff'}">

                                        <div class="phone-content-title"></div>
                                        <div ref="mobile" style="height: 550px;overflow: hidden;overflow-y:scroll;"
                                             v-html="formData.content"></div>
                                    </div>
                                </div>
                            </el-col>
                        </el-row>
                    </el-form>

                </div>
                <div class="panel-body" v-if="showMsg==1">
                    <el-form :model="formData" label-position="top" :rules="rules" ref="formData" label-width="100px"
                             class="demo-ruleForm">

                        <el-col :span="18">
                            <el-form-item required prop="title">
                                <el-input style="width: 100%;top:-15px" v-bind:content="formData.title"
                                          v-model="formData.title" placeholder="请填写标题"></el-input>

                            </el-form-item>
                            <el-form-item required prop="link_url">
                                <el-input style="width: 100%;" v-bind:content="formData.link_url"
                                          v-model="formData.link_url" placeholder="请填写链接地址"></el-input>

                            </el-form-item>
                            <el-form-item required prop="hot">
                                <el-radio-group v-model="formData.hot">
                                    <el-radio border :label="1">正常</el-radio>
                                    <el-radio border :label="2">热门</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item required prop="lock">
                                <el-radio-group v-model="formData.lock">
                                    <el-radio border :label="1">正常</el-radio>
                                    <el-radio border :label="2">锁定</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item required prop="status">
                                <el-radio-group v-model="formData.status">
                                    <el-radio border :label="1">上架</el-radio>
                                    <el-radio border :label="2">下架</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item required prop="thumb">
                                <el-row :gutter="20">
                                    <el-col :span="24" style="padding-left: 5px;">
                                        <el-form-item required label="封面图：" prop="thumb">
                                            <el-upload
                                                class="index-avatar-uploader"
                                                :action="upload"
                                                :headers="myHeaders"
                                                :show-file-list="false"
                                                name="image"
                                                :on-success="handleAvatarSuccess"
                                                :before-upload="beforeAvatarUpload">
                                                <img v-if="formData.thumb" :src="formData.thumb"
                                                     class="index-avatar">
                                                <i v-else class="el-icon-plus index-avatar-uploader-icon"></i>
                                            </el-upload>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="24" style="margin-top:10px;">
                                        <el-tag type="danger" style="margin-bottom:10px;">上传封面图片格式只能是 JPG | PNG |
                                            GIF
                                        </el-tag>
                                        <el-tag type="danger" style="margin-bottom:10px;">上传封面图片大小不能超过 100KB!
                                        </el-tag>
                                        <el-tag type="danger" style="margin-bottom:10px;">上传的封面图宽高必须是 360*288 px !
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-form-item>
                        </el-col>
                        <el-col :span="11">
                            <div>
                                <el-button style="float: right" type="primary" @click="update(formData)">保存发布
                                </el-button>
                                <el-button type="primary" @click="goback()">返回列表</el-button>
                            </div>
                        </el-col>
                    </el-form>

                </div>
            </section>
        </el-main>
    </el-container>
</template>
<script>
    import {mapGetters} from 'vuex';
    import {
        BackAll,
        ArticleInfo,
        ArticleUpdate,
        BackUpdate,
        BackDestroy
    } from '@/utils/request';
    import VueNeditorWrap from 'vue-neditor-wrap';

    export default {
        components: {VueNeditorWrap},
        data() {
            return {
                isModify: false,//是否为修改（编辑）文章
                userInfo: this.$storage.get('userinfo'),
                showTop: 0,//展示头部
                showMsg: 0,//展示显示的文章发布信息
                item: "0",//选择上传或修改文章的名字
                predefineColors: [
                    '#000000',
                    '#FF0000',
                    '#FFFFFF',
                    '#FFFF00',
                    '#00FF00',
                    '#0000FF',
                    '#9F00FF',
                ],
                content: '',
                myConfig: {
                    // 如果需要上传功能,找后端小伙伴要服务器接口地址
                    preserveHeaders: {
                        'Authorization': 'Bearer ' + this.$storage.get('token'),
                        'Accept': 'application/json'
                    },
                    serverUrl: '/manage/upload',
                    // 你的UEditor资源存放的路径,相对于打包后的index.html
                    UEDITOR_HOME_URL: '/NEditor/',
                    // 编辑器不自动被内容撑高
                    autoHeightEnabled: false,
                    // 初始容器高度
                    initialFrameHeight: 540,
                    // 初始容器宽度
                    initialFrameWidth: '100%',
                    // 关闭自动保存
                    enableAutoSave: false,
                    //关闭远程图片是否抓取到本地保存
                    catchRemoteImageEnable: false,
                    //是否启用元素路径，默认是显示
                    elementPathEnabled: false,
                    ////是否开启字数统计
                    wordCount: false,
                    //是否保持toolbar的位置不动,默认true
                    autoFloatEnabled: false
                },
                backimgs: [],//所有背景图
                backimgsTile: '暂未选择',
                backimgsShow: false,
                formData: {
                    is_link: 1,
                    link_url: "",
                    id: 0,
                    title: '',
                    cateid: '',
                    thumb: '',
                    content: '',
                    backimg: '',
                    music: '',
                    title_color: '#000000',
                    music_name: '',
                    hot: 1,
                    lock: 1,
                    status: 1,
                },
                rules: {
                    title: [{required: true, message: '请填写标题', trigger: 'blur'}],
                    thumb: [{required: true, message: '请上传封面图', trigger: 'blur'}],
                    backimg: [{required: true, message: '请选择背景图', trigger: 'blur'}],
                    music: [{required: true, message: '请填写音乐名称', trigger: 'blur'}],
                    music_name: [{required: true, message: '请填写音乐编号', trigger: 'blur'}],
                },
                myHeaders: {
                    'Authorization': 'Bearer ' + this.$storage.get('token'),
                    'Accept': 'application/json'
                },
                editor: null,
            }
        },
        activated() {
            this.$store.dispatch('setActive', '/article');
            this.getBackgroundImg();
            let that = this;
            //给新增的加applet，并且清空formData
            if (this.$route.params.tmpName) {
                that.isModify = false;
                that.formData = {
                    id: 0,
                    title: '',
                    cateid: '',
                    thumb: '',
                    content: '',
                    backimg: '',
                    music: '',
                    title_color: '#000000',
                    music_name: '',
                    hot: 1,
                    lock: 1,
                    status: 1,
                    applet: this.$route.params.tmpName
                }
            } else {
                that.showTop = 1;
                that.isModify = true;
                that.backMsg()
            }
        },
        computed: {
            ...mapGetters(['loading', 'upload']),
        },
        methods: {
            //切换事件
            handleClick(tab, event) {
                if (tab.index == 0) {
                    this.showMsg = 0;
                } else {
                    this.showMsg = 1;
                }
            },
            //选择背景图
            select(backimg) {
                this.backimgsTile = backimg.title;
                this.formData.backimg = backimg.img;
                this.backimgsShow = false;
            },
            //上传封面
            handleAvatarSuccess(res, file) {
                this.formData.thumb = res.data;
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
                const isLt2M = file.size / 1024 < 100;
                if (!isJPG) {
                    this.$message.error('上传封面图片只能是 JPG | PNG | GIF格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传封面图片大小不能超过 100KB!');
                }
                let width = 360;
                let height = 288;
                const isSize = new Promise(function (resolve, reject) {
                    let _URL = window.URL || window.webkitURL;
                    let img = new Image();
                    img.onload = function () {
                        let valid = img.width === width && img.height === height;
                        valid ? resolve() : reject();
                    };
                    img.src = _URL.createObjectURL(file);
                }).then(() => {
                    return file;
                }, () => {
                    this.$message.error('上传的封面图宽高必须是' + width + '*' + height + ' PX !');
                    return Promise.reject();
                });
                return isJPG && isLt2M && isSize;
            },
            ready(editor) {
                this.editor = editor;
                // this.editor.setPlaceholder('请输入内容');
            },
            //得到全部背景
            getBackgroundImg() {
                BackAll().then((response) => {
                    if (response.code) {
                        this.$message.error(response.msg);
                    } else {
                        this.backimgs = response.data;
                    }
                })
            },
            backMsg() {
                let that = this;
                ArticleInfo({
                    params: {
                        id: this.$route.params.id,
                        applet: this.$route.params.name
                    }
                }).then((res) => {
                    if (res.data.is_link == "1") {
                        //文字形式的内容修改
                        let that = this
                        this.showMsg = 0
                        this.content = res.data.content
                        this.formData = {
                            id: res.data.id,
                            title: res.data.title,
                            thumb: res.data.thumb,
                            cateid: res.data.cateid,
                            title_color: res.data.title_color,
                            content: res.data.content,
                            backimg: res.data.backimg,
                            music: res.data.music,
                            music_name: res.data.music_name,
                            hot: res.data.hot,
                            lock: res.data.lock,
                            status: res.data.status,
                        };
                        setTimeout(function () {
                            that.formData.content = res.data.content;
                        }, 1000);
                    } else {
                        //链接形式的内容修改
                        that.showMsg = 1
                        this.content = res.data.content
                        this.formData = {
                            id: res.data.id,
                            title: res.data.title,
                            thumb: res.data.thumb,
                            cateid: res.data.cateid,
                            backimg: res.data.backimg,
                            hot: res.data.hot,
                            lock: res.data.lock,
                            status: res.data.status,
                            link_url: res.data.link_url,
                        };
                    }
                    this.backimgs.filter((back) => {
                        if (back.img == res.data.backimg) {
                            this.backimgsTile = back.title;
                        }
                    })
                });
            },
            goback() {
                this.$router.push({name: 'Article'})
            },
            //更新
            update(formName) {
                if (this.showMsg == 0) {
                    this.formData.content = this.editor.getContent()
                    if (!this.formData.thumb) {
                        this.$message.error('请上传封面图片');
                        return false;
                    }
                    if (!this.formData.content) {
                        this.$message.error('请填写文章内容');
                        return false;
                    }
                    if (!this.formData.title) {
                        this.$message.error('请填写标题');
                        return false;
                    }
                    if (!this.formData.music_name) {
                        this.$message.error('请填写音乐名称');
                        return false;
                    }
                    if (!this.formData.music) {
                        this.$message.error('请填写音乐编号');
                        return false;
                    }
                    this.formData.is_link = 1;
                    this.saveMsg()
                } else {
                    if (!this.formData.thumb) {
                        this.$message.error('请上传封面图片');
                        return false;
                    }
                    if (!this.formData.title) {
                        this.$message.error('请填写标题');
                        return false;
                    }
                    this.formData.is_link = 2;
                    this.saveMsg()
                }
            },
            saveMsg() {
                if (!this.formData.applet) {
                    this.formData.applet = this.$route.params.name
                }
                ArticleUpdate(this.formData).then((response) => {
                    if (response.code) {
                        this.$message.error(response.msg);
                    } else {
                        this.$message({
                            type: 'success',
                            duration: '1000',
                            message: response.msg,
                            onClose: () => {
                                this.$router.push({name: 'Article'})
                            }
                        });
                    }
                });
            },
        },
    }
</script>
<style scoped>
    .cms-left-btn {
        float: left;
    }

    .el-tab-pane {
        display: none;
    }

    .backimgs {
        max-height: 550px;
        overflow: hidden;
        overflow-y: scroll;
    }

    .index-avatar-uploader .el-upload {

        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .index-avatar-uploader-icon {
        border: 1px dashed #d9d9d9;
        font-size: 28px;
        color: #8c939d;
        width: 360px;
        height: 288px;
        line-height: 288px;
        text-align: center;
    }

    .preview-art {
        background-image: url(../../assets/img/phone.png);
        background-repeat: no-repeat;
        background-size: 100% 100%;
        height: 780px;
        padding: 75px 16px;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        width: 424px;
        display: inline-block;

    }

    .phone-content-title {
        background-repeat: no-repeat;
        background-size: 100% 100%;
        height: 55px;
        width: 100%;
        background-image: url(../../assets/img/titlebar.png);
    }

</style>
